--===========================================================================--
-- Naziv		: Write back
-- Ime fajla	: wb.vhdl  
-- Verzija		: 0.2
--===========================================================================-- 

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity wb is 
	  port (
		  --IN
			reset,clk 	  : in  std_logic; 
			result         : in std_logic_vector (15 downto 0 );
			opcode_ex      : in std_logic_vector(4 downto 0);
			R1_ex,R2_ex,R3_ex     : in std_logic_vector (3 downto 0 );
			D_DBUS_ex          : in std_logic_vector(15 downto 0);
		   
		  --OUT
			Reg_wb              : out std_logic_vector(3 downto 0); 
			Data_wb           : out std_logic_vector(15 downto 0);
			write_wb            : out std_logic
	  );
end;

architecture wb_AR of wb is
signal opcode_wb       :  std_logic_vector(4 downto 0);
signal R1_wb,R2_wb,R3_wb     :  std_logic_vector (3 downto 0 );
signal result_wb       :  std_logic_vector (15 downto 0 );
signal D_DBUS_wb     : std_logic_vector(15 downto 0);

begin
	wb_PR: process (clk,reset) is
	begin
		if reset='1' then
			R1_wb<="0000";
			R2_wb<="0000";
			R3_wb<="0000";
			result_wb<="0000000000000000";
			opcode_wb<=	"00000";
			D_DBUS_wb <="0000000000000000";
		elsif rising_edge(clk)  then  
			R1_wb<=R1_ex;
			R2_wb<=R2_ex;
			R3_wb<=R3_ex;
			result_wb<=result;		
			opcode_wb<=	opcode_ex;
			D_DBUS_wb <=D_DBUS_ex;
		end if;
	end process;
	
	Data_wb<= result_wb   when ((opcode_wb>"00000" and opcode_wb<"01001")or opcode_wb="10100" or opcode_wb="10111" ) else --MOV-POPREL i POP i NOT
		      D_DBUS_wb when opcode_wb="10001" else --LOAD
			  "0000000000000000";
			
    write_wb <=	'1' when ((opcode_wb>"00000" and opcode_wb<"01001")or opcode_wb="10100" or opcode_wb="10111" or opcode_wb="10001") else --MOV-POPREL i POP i NOT
				'0';

	Reg_wb<= R1_wb when (opcode_wb="01000" or opcode_wb="10100") else  --POPREL, POP
			 R2_wb when (opcode_wb="10001" or opcode_wb="10111") else  --LOAD, NOT
			 R3_wb when (opcode_wb>="00001" and opcode_wb<="00111") else --MOV,ROR,ADD,SUB,AND,OR,XOR
			 "0000";	  
	
end wb_AR;